// CChooseDevice.cpp : implementation file
//

#include "pch.h"
#include "CameraPreview.h"
#include "CChooseDevice.h"
#include "afxdialogex.h"


// CChooseDevice dialog

IMPLEMENT_DYNAMIC(CChooseDeviceDlg, CDialogEx)

CChooseDeviceDlg::CChooseDeviceDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_CHOOSE_DEVICE, pParent)
    , m_pParam(NULL)
{

}

CChooseDeviceDlg::~CChooseDeviceDlg()
{
}

void CChooseDeviceDlg::DoDataExchange(CDataExchange* pDX)
{
    CDialogEx::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_DEVICE_LIST, m_listDevice);
}

BOOL CChooseDeviceDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

    HRESULT hr = S_OK;

    // Display a list of the devices.

    for (DWORD i = 0; i < m_pParam->count; i++)
    {
        WCHAR* szFriendlyName = NULL;

        hr = m_pParam->ppDevices[i]->GetAllocatedString(
            MF_DEVSOURCE_ATTRIBUTE_FRIENDLY_NAME,
            &szFriendlyName,
            NULL
        );

        if (FAILED(hr))
        {
            break;
        }

        int index = m_listDevice.AddString(szFriendlyName);
        m_listDevice.SetItemData(index, i);
        CoTaskMemFree(szFriendlyName);
    }

    // Assume no selection for now.
    m_pParam->selection = (UINT32)-1;

    if (m_pParam->count == 0)
    {
        // If there are no devices, disable the "OK" button.
        GetDlgItem(IDOK)->EnableWindow(FALSE);
    }
    else
    {
        // Select the first device in the list.
        m_listDevice.SetCurSel(0);
    }

	return TRUE;
}


BEGIN_MESSAGE_MAP(CChooseDeviceDlg, CDialogEx)
    ON_BN_CLICKED(IDOK, &CChooseDeviceDlg::OnBnClickedOk)
END_MESSAGE_MAP()


// CChooseDevice message handlers


void CChooseDeviceDlg::OnBnClickedOk()
{
    // TODO: Add your control notification handler code here
    
    // Get the current selection and return it to the application.
    int sel = m_listDevice.GetCurSel();
    if (sel != LB_ERR)
    {
        m_pParam->selection = (UINT32)m_listDevice.GetItemData(sel);
    }

    CDialogEx::OnOK();
}
